<template>
  <!-- 搜索框 -->
  <div class="banner">
    <div class="bannerTop">
      <a-input-search
        class="search"
        v-model:value="keywords"
        :placeholder="$t('search.placeholder')"
        enter-button
        @search="onSearch"
        allowClear
      />
      <!-- 跳转添加 -->
      <a-space>
        <a-button @click="refresh">
          <template #icon>
            <AppleOutlined />
          </template>
          刷新
        </a-button>
        <a-button type="primary" @click="toAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          开启
        </a-button>
      </a-space>
    </div>
    <!-- 表格数据 -->
    <a-table
      :columns="columns"
      :rowKey="(record) => record.id"
      :data-source="data"
      :row-selection="rowSelection"
      :pagination="false"
      :loading="isLoading"
    >
      <!-- 操作自定义插槽  -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-button-group>
            <a-button
              size="small"
              ghost
              type="primary"
              @click="toEditor(record)"
              >{{ $t("banner.edit") }}</a-button
            >
            <a-button size="small" ghost danger @click="remove(true, record)">{{
              $t("banner.delete")
            }}</a-button>
          </a-button-group>
        </template>
        <!-- 图片 -->
        <template v-if="column.dataIndex === 'pic'">
          <a-image :width="80" :hight="80" :src="record.pic" />
        </template>
        <!-- 状态 -->
        <template v-if="column.dataIndex === 'status'">
          <a-tag color="#87d068" v-if="record.status">
            {{ $t("btn.start") }}
          </a-tag>
          <a-tag color="#f50" v-else>关闭</a-tag>
        </template>
      </template>
    </a-table>

    <!-- 分页 -->
    <div class="footer">
      <a-button :disabled="selectedData.length === 0" @click="remove(false)">{{
        $t("banner.deleteTheSelection")
      }}</a-button>
      <a-pagination
        v-model:current="paga"
        :total="total"
        :page-size-options="pageSizeOptions"
        v-model:pageSize="limit"
        show-size-changer
        @showSizeChange="onShowSizeChange"
        hideOnSinglePage
        :scroll="{ y: 'calc(100vh - 288px' }"
      >
        <template #buildOptionText="props">
          <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
        </template>
        <template #itemRender="{ type, originalElement }">
          <a v-if="type === 'prev'">{{ $t("banner.previous") }}</a>
          <a v-else-if="type === 'next'">{{ $t("banner.next") }}</a>
          <component :is="originalElement" v-else></component>
        </template>
      </a-pagination>
    </div>
  </div>
</template>

<script setup>
import { PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { h, ref, watch } from "vue";
import { useRouter } from "vue-router";
import columns from "./table.columns";
import { getBannerListApi, delBannerApi } from "../../../api/banner";
//拼接路径
import { handlerPicPath } from "../../../utils/tools";
//model
import { message as Mag, Modal } from "ant-design-vue";
const router = useRouter();
const keywords = ref("");
const data = ref([]);
//页码
const selectedData = ref([]); //多选
//分页
const paga = ref(1); //当前页
const limit = ref(10); //每页多少条
const total = ref(0); //总页数
const isLoading = ref(false); //表格的isLoading
//下拉
const pageSizeOptions = ref(["10", "20", "30", "40", "50"]);
const onShowSizeChange = (current, pageSize) => {
  //每页的数据发生变化：current当前页 pageSize每页个数
  limit.value = pageSize;
  getList();
};
watch(paga, () => {
  console.log(111);
  getList();
});
//请求数据
const getList = async () => {
  isLoading.value = true;
  const params = {
    paga: paga.value,
    limit: limit.value,
    keyword: keywords.value,
  };
  const res = await getBannerListApi(params);
  isLoading.value = false;
  data.value = handlerPicPath(res.data);
  total.value = res.total;
};
getList();

//多选
const rowSelection = ref({
  checkStrictly: false,
  onChange: (selectedRowKeys, selectedRows) => {
    selectedData.value = selectedRows;
    console.log(selectedRows);
  },
  onSelect: (record, selected, selectedRows) => {
    selectedData.value = selectedRows;
    console.log(selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    selectedData.value = selectedRows;
    console.log(changeRows);
  },
});
//多选结束
const toAdd = () => {
  router.push({ name: "bannerAdd" });
};
const toEditor = ({ id }) => {
  router.push({ name: "bannerEdit", params: { id } });
};
//搜索
const onSearch = () => {
  getList();
};
//删除
const remove = (isOne, record) => {
  const params = [];
  let message = "";
  if (isOne) {
    const { name, id } = record;
    params.push(id);
    message = name;
  } else {
    //多选
    const ids = selectedData.value.map((item) => item.id);
    params.push(...ids);
    message = ids.length + "条数据";
  }
  console.log(params, message);
  //1.拦截弹框 -> 2.是 ->请求api ->3.成功提示->表格数据刷新
  Modal.confirm({
    title: "温馨提示：",
    icon: h(ExclamationCircleOutlined),
    content: `你确定要删除当前数据吗 [${message}]`,
    async onOk() {
      try {
        return await delBannerApi(params).then((res) => {
          console.log(res);
          if (res.affected > 0) {
            //删除成功
            Mag.success("恭喜你，删除成功");
          } else {
            Mag.fail("操作失败");
          }
          //刷新当前页面
          getList();
        });
      } catch (e) {
        console.log(e);
      }
    },
    onCancel() {},
    maskClosable: true,
  });
};
</script>

<style scoped lang="less">
.banner {
  padding: 0 20px;

  .bannerTop {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .search {
      max-width: 300px;
    }
  }
  .footer {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
  }
}
</style>
